﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using BDSync.Domains.DataContext;
using BDSync.Domains.Entities;
using LiteDB;

namespace BDSync.Domains.DBConn
{
    public class DBConnRepo
    {
        protected LiteDatabase db;
        protected ILiteCollection<DBConnObj> EntitySet;

        public DBConnRepo()
        {
            db = DBContext.GetDB();
            EntitySet = db.GetCollection<DBConnObj>(typeof(DBConnObj).Name);
        }


        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual BsonValue Insert(DBConnObj entity)
        {
            var id = EntitySet.Insert(entity);
            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual bool Update(DBConnObj entity)
        {
            var res = EntitySet.Update(entity);
            return res;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual bool Delete(DBConnObj entity)
        {
            var res = EntitySet.Delete(entity.Id);
            return res;
        }

        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public virtual DBConnObj FindById(BsonValue Id)
        {
            var entity = EntitySet.FindById(Id);
            return entity;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="propName"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual IEnumerable<DBConnObj> Findby(string propName, Expression<Func<DBConnObj, bool>> predicate)
        {
            EntitySet.EnsureIndex(propName);
            var res = EntitySet.Find(predicate);
            return res;
        }


        /// <summary>
        /// 查询一个
        /// </summary>
        /// <param name="propName"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public virtual DBConnObj FindOne(string propName, Expression<Func<DBConnObj, bool>> predicate)
        {
            EntitySet.EnsureIndex(propName);
            var res = EntitySet.FindOne(predicate);
            return res;
        }

        /// <summary>
        /// 查找全部
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable<DBConnObj> FindAll()
        {
            var res = EntitySet.FindAll();
            return res;
        }


    }
}
